<template>
  <div class="profile-image">
    <img :src="image" ref="image"  width="100%" height="100%">
    <van-nav-bar
        class="toolbar"
        left-text="取消"
        @click-left="$emit('close')"
        @click-right="onConfirm"
        right-text="确认"/>
  </div>
</template>

<script>
import {updateUserPhoto} from "@/api/user";
import Cropper from 'cropperjs'
import 'cropperjs/dist/cropper.css'

export default {
  name: "profileImage",
  props:{
    file:{
      // type:String,
      required:true
    },
  },
  data(){
    return{
      image:window.URL.createObjectURL(this.file),
      cropper:null
    }
  },
  mounted() {
    const image=this.$refs.image
    this.cropper=new Cropper(image,{
      viewMode: 1, // 查看模式
      dragMode: 'move', // 拖动模式
      aspectRatio: 1, // 截图比例
      autoCropArea: 1, // 自动区域
      cropBoxMovable: false, // 不允许截图区域移动
      cropBoxResizable: false, // 不允许截图区域缩放
      modal: true, // 显示阴影区域
      // movable: false
      background: false, // 关闭背景
      movable: true, // 允许移动
      })
  },
  methods:{
    getCroppedCanvas(){
      return new Promise(resolve => {
        this.cropper.getCroppedCanvas().toBlob((file => {
          resolve(file)
        }))
      })
    },
    async onConfirm(){
      this.$toast.loading({
        message:'保存中',
        forbidClick:true
      })
      const file=await this.getCroppedCanvas()
      const fd=new FormData()
      fd.append('photo',file)
      await updateUserPhoto(fd)
      this.$toast.success('保存成功')
      this.$emit('update-photo',window.URL.createObjectURL(file))
      this.$emit('close')
    }
  }
}
</script>

<style scoped lang="less">
.profile-image{
  margin-top: 150px;
}
/deep/.van-nav-bar__content{
  background-color: black;
}
.image{
  display: block;
}
.toolbar{
  position: fixed;
  left: 0;
  right: 0;
  bottom: 0;
}
</style>